package com.zaimokuza.cn.controller;

import com.zaimokuza.cn.entity.PageResult;
import com.zaimokuza.cn.entity.blog.Comment;
import com.zaimokuza.cn.entity.response.ResponseFormat;
import com.zaimokuza.cn.service.CommentService;
import com.zaimokuza.cn.util.RandomUtils;
import com.zaimokuza.cn.util.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;

/**
 * @author zaimokuza
 */
@Api(tags = "评论相关")
@ResponseFormat
@RestController
@RequestMapping("/comment")
public class CommentController {

    @Resource
    private CommentService commentService;

    @ApiOperation(value = "添加评论", notes = "添加评论，对属性会进行校验")
    @PostMapping("/add")
    @Transactional(rollbackFor = Exception.class)
    public String addComment(@Validated @RequestBody Comment comment) {
        // 评论ID
        String uid = RandomUtils.get32Uid();
        comment.setId(uid);
        // 用户ID
        comment.setUserId(UserUtils.getUserId());
        // 添加评论
        commentService.addComment(comment);
        // 返回评论ID
        return uid;
    }

    @ApiOperation(value = "用户删除评论", notes = "用户根据ID删除评论")
    @DeleteMapping("/delete")
    @Transactional(rollbackFor = Exception.class)
    public void deleteCommentForUser(@RequestParam @ApiParam("评论ID") String id) {
        commentService.deleteCommentForUser(id, UserUtils.getUserId());
    }

    @ApiOperation(value = "管理端删除评论", notes = "管理端根据ID删除评论")
    @DeleteMapping("/manageDelete")
    @Transactional(rollbackFor = Exception.class)
    public void deleteCommentForManage(@RequestParam @ApiParam("评论ID") String id) {
        commentService.deleteCommentForUser(id, UserUtils.getUserId());
    }

    @ApiOperation(value = "查询评论列表", notes = "根据博客ID查询评论列表")
    @GetMapping("/list")
    public ArrayList<Comment> getCommentList(@RequestParam String blogId, @RequestParam(required = false) String time) {
        return commentService.getCommentList(blogId, UserUtils.getUser() == null ? null : UserUtils.getUserId(), time);
    }

    @ApiOperation(value = "查询分页的评论列表", notes = "查询分页的评论列表")
    @GetMapping("/page")
    public PageResult<Comment> getCommentPage(@RequestParam(required = false) @ApiParam("博客名称") String blogName,
                                              @RequestParam(required = false) @ApiParam("用户名称") String userName,
                                              @RequestParam(required = false) @ApiParam("评论内容") String content,
                                              @RequestParam Integer page,
                                              @RequestParam(defaultValue = "10") Integer size) {
        return commentService.getCommentPage(blogName, userName, content, page, size);
    }

}
